<template>
    <div class="enterprise-container">
        <!-- 筛选区域 -->
        <div class="filter-bar">
            <div class="filter-item">
                <span>时间范围</span>
                <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD"
                />
            </div>

            <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
        </div>

        <!-- 主内容区 -->
        <div class="content-wrapper">
            <!-- 左侧图表 -->
            <div class="chart-section">
                <h3>企业数据统计</h3>
                <div ref="chartRef" class="chart-container"></div>
            </div>

            <!-- 右侧表格 -->
            <div class="table-section">
                <el-table :data="tableData" style="width: 100%" border v-loading="loading">
                    <el-table-column type="index" label="序号" width="60" />
                    <el-table-column prop="merchants" label="招商员" />
                    <el-table-column prop="totalCompanyCount" label="企业数(个)" />
                    <el-table-column prop="entityCount" label="实体(个)" />
                    <el-table-column prop="hangkouCount" label="挂靠(个)" />
                    <el-table-column prop="unProcessedCount" label="未办结(个)" />
                    <el-table-column prop="processedCount" label="已办结(个)" />
                </el-table>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getCompanyTotalData } from '@/api/AttractInvestment/contact/index.js'

// 响应式数据
const dateRange = ref([])
const tableData = ref([])
const loading = ref(false)

// 图表实例
const chartRef = ref(null)
let chartInstance = null

// 设置默认日期范围（最近30天）
const setDefaultDateRange = () => {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 30)

    dateRange.value = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0]
    ]
}

// 处理接口数据
const fetchChartData = async () => {
    loading.value = true
    try {
        if (!dateRange.value || dateRange.value.length !== 2) {
            console.error('日期范围参数错误')
            return { chartData: [], tableList: [] }
        }
        const formatDate = (date) => {
        if (!date) return ''
        if (typeof date === 'string') return date // 如果已经是字符串格式直接返回
        // 如果是 Date 对象则格式化
        return date.toISOString().split('T')[0]
}

        const params = {
            startDate: formatDate(dateRange.value[0]),
            endDate: formatDate(dateRange.value[1])
        }

        console.log('请求参数:', params)
        const res = await getCompanyTotalData(params)
        console.log('接口返回数据:', res)

        // 检查返回数据
        if (!res || res.code !== 200) {
            console.error('接口返回错误:', res?.msg)
            return { chartData: [], tableList: [] }
        }

        const rows = res.rows || []
        console.log('表格数据行:', rows)

        // 计算图表数据 - 根据所有行的数据汇总
        const chartData = [
            {
                name: '企业数',
                value: rows.reduce((sum, item) => sum + (item.totalCompanyCount || 0), 0)
            },
            {
                name: '实体',
                value: rows.reduce((sum, item) => sum + (item.entityCount || 0), 0)
            },
            {
                name: '挂靠',
                value: rows.reduce((sum, item) => sum + (item.hangkouCount || 0), 0)
            },
            {
                name: '未办结',
                value: rows.reduce((sum, item) => sum + (item.unProcessedCount || 0), 0)
            },
            {
                name: '已办结',
                value: rows.reduce((sum, item) => sum + (item.processedCount || 0), 0)
            }
        ]

        // 处理表格数据 - 直接使用接口返回的 rows
        const tableList = rows.map((item, index) => ({
            index: index + 1,
            merchants: item.merchants || '未知招商员',
            totalCompanyCount: item.totalCompanyCount || 0,
            entityCount: item.entityCount || 0,
            hangkouCount: item.hangkouCount || 0,
            unProcessedCount: item.unProcessedCount || 0,
            processedCount: item.processedCount || 0
        }))

        console.log('处理后的图表数据:', chartData)
        console.log('处理后的表格数据:', tableList)

        return {
            chartData,
            tableList
        }
    } catch (error) {
        console.error('获取数据失败:', error)
        return {
            chartData: [],
            tableList: []
        }
    } finally {
        loading.value = false
    }
}

// 初始化图表
const initChart = (data) => {
    if (!chartRef.value) {
        console.error('图表容器未找到')
        return
    }

    // 销毁旧实例
    if (chartInstance) {
        chartInstance.dispose()
    }

    chartInstance = echarts.init(chartRef.value)

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: '{b}: {c}'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
                rotate: 45,
                interval: 0
            }
        },
        yAxis: {
            type: 'value',
            min: 0
        },
        series: [{
            name: '数量',
            type: 'bar',
            data: data.map(item => item.value),
            itemStyle: {
                color: function(params) {
                    const colors = ['#1890ff', '#f5222d', '#52c41a', '#faad14', '#722ed1']
                    return colors[params.dataIndex % colors.length]
                }
            },
            label: {
                show: true,
                position: 'top',
                formatter: '{c}'
            }
        }]
    }

    chartInstance.setOption(option)

    // 添加窗口resize监听
    const handleResize = () => {
        chartInstance.resize()
    }
    window.addEventListener('resize', handleResize)
}

// 查询处理
const handleSearch = async () => {
    const result = await fetchChartData()
    console.log('查询结果:', result)

    // 直接赋值表格数据
    tableData.value = result.tableList

    // 使用 nextTick 确保DOM更新后再初始化图表
    nextTick(() => {
        if (result.chartData && result.chartData.length > 0) {
            initChart(result.chartData)
        } else {
            console.warn('图表数据为空')
            // 如果没有数据，显示空图表
            initChart([
                { name: '企业数', value: 0 },
                { name: '实体', value: 0 },
                { name: '挂靠', value: 0 },
                { name: '未办结', value: 0 },
                { name: '已办结', value: 0 }
            ])
        }
    })
}

// 页面加载时初始化
onMounted(async () => {
    setDefaultDateRange()
    await handleSearch()
})
</script>

<style scoped>
.enterprise-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.filter-bar {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
    background: white;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-item span {
    font-size: 14px;
    color: #666;
}

.content-wrapper {
    display: flex;
    gap: 20px;
}

.chart-section, .table-section {
    flex: 1;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chart-section h3 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
    text-align: center;
}

.chart-container {
    width: 100%;
    height: 400px;
    min-height: 400px;
}

.table-section {
    min-width: 600px;
}

/* 确保表格区域有最小高度 */
.table-section :deep(.el-table) {
    min-height: 400px;
}
</style>